import fs from "node:fs";
import readline from "readline";
import CryptoJS from "crypto-js";

const dataPath = 'pages/Doc';
// 存储数据路径
const activityDataPath = "pages/Data/activity.json";
const newsDataPath = "pages/Data/news.json";
const courseDataPath = "pages/Data/course.json";

// 处理数据
const getDataJson = async() => {
  const lanFiles = fs.readdirSync(dataPath);
  let aData = {};
  let nData = {};
  let cData = {};
  for await (const file of lanFiles) {
    try {
      const files = fs.readdirSync(`${dataPath}/${file}`);
      for await (const item of files) {
        if(item === 'activity') {
          const activity = await getActivity(`${dataPath}/${file}/${item}`);
          if(activity?.length) {
            aData[file] = activity;
          }
        } else if(item === 'news') {
          const news = await getArticle(`${dataPath}/${file}/${item}`)
          nData[file] = news;
        } else if(item === 'course') {
          const course = await getActivity(`${dataPath}/${file}/${item}`)
          cData[file] = course;
        }
      }
    } catch {}
  }
  fs.writeFileSync(activityDataPath, JSON.stringify(aData));
  fs.writeFileSync(newsDataPath, JSON.stringify(nData));
  fs.writeFileSync(courseDataPath, JSON.stringify(cData));
}
getDataJson();

// 获取活动数据
const getActivity = async(path) => {
  const activityFiles = fs.readdirSync(path);
  const activityData = await getData(activityFiles, path);
  return activityData;
}

// 获取文章数据
const getArticle = async(path) => {
  const files = fs.readdirSync(path);
  if(files?.length) {
    const newsData = {};
      for await (const file of files) {
        try {
          const newsFiles = fs.readdirSync(`${path}/${file}`);
          newsData[file] = await getData(newsFiles, `${path}/${file}`);
        } catch {}
      }
    return newsData
  }
}

// 获取某个文件数据
const getData = async (files, path) => {
  const data = [];
  for await (const file of files) {
    try {
      const key = await getKeyData(file, path);
      const id = CryptoJS.MD5(file).toString();
      data.push({
        id,
        path: `${path}/${file}`,
        ...key,
      });
    } catch {}
  }
  return data;
};

// 获取md文件里面的信息
const getKeyData = async (file, path) => {
  const keyValue = {};
  const readStream = fs.createReadStream(`${path}/${file}`);
  const rl = readline.createInterface({
    input: readStream,
    crlfDelay: Infinity,
  });
  let isStart = false;
  for await (const line of rl) {
    if (line === "---") {
      if (isStart) {
        isStart = false;
        rl.close();
      } else {
        isStart = true;
      }
    } else if (isStart && line) {
      try {
        const [content, key, value] = line.match(/^(\w+)[:：](.*)$/);
        keyValue[key] = value.trim();
      } catch {}
    }
  }
  return keyValue;
};
